var Base64 = require('../libs/js-base64/base64.modified.js');
let demain = 'baicai.fanxl.cn'
//let demain = '192.168.0.186:8085'
var serverUrl = 'http://' + demain + "/t"
var host = serverUrl + '/api/v1/';
var clientId = 'tickey';
var clientSecret = 'tickey123';

var notAuthorizeRequest = function (url, method, data, header, loadType, success, fail, complete) {
  if (loadType == 1) {
    wx.showLoading({
      title: '加载中...'
    });
  } else if (loadType === 4) {
    wx.showNavigationBarLoading();
  }
  if (header == null) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }
  wx.request({
    url: host + url,
    data: data,
    method: method,
    header: header,
    success: function (res) {
      var response = res.data;
      if (response.success) {
        success.success(response.result);
      } else {
        fail.fail(response.message);
      }
    },
    fail: function (res) {
      fail.fail(res);
    },
    complete: function () {
      if (complete !== undefined) {
        complete.complete();
      }
      if (loadType == 1) {
        wx.hideLoading();
      } else if (loadType === 4) {
        wx.hideNavigationBarLoading();
      }
    }
  })
}

var sendRequest = function (url, method, data, header, loadType, success, fail) {
  var tokenInfo = wx.getStorageSync('tokenInfo');
  var userInfo = wx.getStorageSync('userInfo');
  var tokenExpireTime = tokenInfo.expireTime;
  var saveTime = tokenInfo.saveTime;
  var token = tokenInfo.token;
  var tokenType = tokenInfo.tokenType;
  var accessToken = tokenType + ' ' + token;
  if (userInfo === undefined) {
    fail.fail('toRegister');
  } else {
    if (tokenInfo === undefined || tokenInfo === null || tokenInfo === '') {
      tLogin(url, method, data, header, success, fail, userInfo.unionId);
      return
    }
    var tokenSaveTime = new Date(Date.parse(saveTime));
    tokenSaveTime.setSeconds(tokenSaveTime.getSeconds() + tokenExpireTime);
    var currentTime = new Date();
    var time = (tokenSaveTime.getTime() - currentTime.getTime()) / 1000;
    console.log('时间差:' + time);
    if (time <= -0) {
      tLogin(url, method, data, header, success, fail, userInfo.unionId);
    } else if (time <= 600) {
      var refreshToken = tokenInfo.refreshToken;
       (url, method, data, header, success, fail, refreshToken, loadType);
    } else {
      startRequest(url, method, data, header, success, fail, accessToken, loadType);
    }
  }
}

var startRequest = function (url, method, data, vHeader, success, fail, accessToken, loadType) {
  console.log('开始真正请求');
  if (loadType == 1) {
    wx.showLoading({
      title: '加载中...',
    });
  } else if (loadType === 4) {
    wx.showNavigationBarLoading();
  }
  var header = vHeader;
  if (header == null) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }
  header.Authorization = accessToken;
  wx.request({
    url: host + url,
    data: data,
    method: method,
    header: header,
    success: function (res) {
      var response = res.data;
      if (response.success) {
        success.success(response.result);
      } else {
        let error = response.error;
        if (error === 'invalid_token') {
          console.log('token失效，重新登录');
          var userInfo = wx.getStorageSync('userInfo');
          tLogin(url, method, data, header, success, fail, userInfo.unionId);
        } else {
          fail.fail(response.message);
        }
      }
    },
    fail: function (res) {
      console.log('错误了');
      fail.fail(res);
    },
    complete: function () {
      if (loadType == 1) {
        wx.hideLoading();
      } else if (loadType === 4) {
        wx.hideNavigationBarLoading();
      }
    }
  })
}

var tLogin = function (unionId, accountSuite) {
  console.log(accountSuite)
  var encode = Base64.encode(clientId + ':' + clientSecret);
  var authorization = 'Basic ' + encode;
  wx.request({
    url: serverUrl + "/authentication/openid",
    data: {
      openId: unionId,
      providerId: accountSuite
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': authorization
    },
    method: 'POST',
    success: function (res) {
      let  response = res.data
      if (!response.success && response===null) {
        console.log('登录失败', res);
        wx.redirectTo({
          url: '../binding/binding',
        })
      } else {
        console.log("登录成功", res);
        var tokenInfo = {};
        tokenInfo.token = response.result.access_token;
        tokenInfo.expireTime = response.result.expires_in;
        tokenInfo.saveTime = new Date();
        tokenInfo.refreshToken = response.result.refresh_token;
        tokenInfo.tokenType = response.result.token_type;
        wx.setStorage({
          key: 'tokenInfo',
          data: tokenInfo,
        });
        var accessToken = tokenInfo.tokenType + ' ' + tokenInfo.token;
        console.log(accessToken)
        //startRequest(url, method, data, vHeader, success, fail, accessToken);
        wx.switchTab({
          url: '../home/home'
        })
      }
    },
    fail: function (res) {
      console.log("登录失败", res);

    }
  })
}

var refreshTokenRequest = function (url, method, data, vHeader, success, fail, refreshToken, loadType) {
  var encode = Base64.encode(clientId + ':' + clientSecret);
  var authorization = 'Basic ' + encode;
  console.log('开始刷新token');
  var that = this;
  if (loadType == 1) {
    wx.showLoading({
      title: '加载中...',
    });
  } else if (loadType === 4) {
    wx.showNavigationBarLoading();
  }
  wx.request({
    url: serverUrl + '/oauth/token',
    data: {
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
      scope: 'all'
    },
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': authorization
    },
    success: function (res) {
      var response = res.data
      if (response.access_token === undefined) {
        wx.setStorage({
          key: 'tokenInfo',
          data: undefined
        });
        wx.setStorage({
          key: 'userInfo',
          data: undefined
        })
        fail.fail('请求异常');
      } else {
        var tokenInfo = {};
        tokenInfo.token = response.access_token;
        tokenInfo.expireTime = response.expires_in;
        tokenInfo.saveTime = new Date();
        tokenInfo.refreshToken = response.refresh_token;
        tokenInfo.tokenType = response.token_type;
        wx.setStorage({
          key: 'tokenInfo',
          data: tokenInfo,
        });
        var accessToken = tokenInfo.tokenType + ' ' + tokenInfo.token;
        startRequest(url, method, data, vHeader, success, fail, accessToken, loadType);
      }
    },
    fail: function (res) {
      console.log(res);
      fail.fail(res);
    },
    complete: function () {
      if (loadType == 1) {
        wx.hideLoading();
      } else if (loadType === 4) {
        wx.hideNavigationBarLoading();
      }
    }
  })
}

function toastError(text) {
  toastShow(text, "/images/error.png");
}

function toastHttpError(text) {
  setTimeout(function () {
    toastShow(text, "/images/error.png");
  }, 1000);
}

function toastTips(text) {
  wx.showToast({
    title: text,
    icon: 'success'
  })
}

function showModule(text) {
  wx.showModal({
    title: "温馨提示",
    content: text,
    showCancel: false,
    confirmText: "确定"
  })
}

  

function toastShow(text, image) {
  wx.showToast({
    title: text,
    image: image,
    duration: 2000
  })
}

module.exports = {
  serverUrl: serverUrl,
  host: host,
  clientId: clientId,
  clientSecret: clientSecret,
  notAuthorizeRequest: notAuthorizeRequest,
  tLogin: tLogin,
  sendRequest: sendRequest,
  toastError: toastError,
  toastTips: toastTips,
  toastHttpError: toastHttpError,
  showModule: showModule
} 